//
//  THMainViewController.m
//  Teacher-Help
//
//  Created by Taro on 15/10/21.
//  Copyright © 2015年 Taro. All rights reserved.
//

#import "THMainViewController.h"
#import <AFNetworking/AFNetworking.h>
#import <Masonry/Masonry.h>
#import "THRollcallViewController.h"
#import "THHistoryViewController.h"
#import "THClass.h"
#import "THButton.h"
#import "THDetailOfHistoryViewController.h"



@interface THMainViewController ()<UIScrollViewDelegate,UITableViewDelegate,UITableViewDataSource,UITableViewDataSource>

@property (strong,nonatomic)UIButton * currentBtn;
@property (nonatomic , strong) UIButton * tmpBtn;
@property (nonatomic , strong) UIView * bgView;
@property (nonatomic , strong) UIScrollView * scrollbg;
@property (nonatomic , strong) UITableView * tableview;
@property (nonatomic , strong) NSMutableArray * btnArray;
@property (nonatomic , strong) NSMutableArray * tableArray;
@property (nonatomic , strong) NSMutableArray * resultArray;
@property (nonatomic , strong) NSMutableArray * resultmodel;
@property (nonatomic , assign) NSInteger week;
@property (nonatomic , strong) NSMutableDictionary * result;
@property (nonatomic , strong) NSNumber * courseId;
@property (nonatomic , strong) NSNumber * weekOrdinal;



@property (nonatomic , strong) NSMutableArray * mon;
@property (nonatomic , strong) NSMutableArray * tues;
@property (nonatomic , strong) NSMutableArray * wed;
@property (nonatomic , strong) NSMutableArray * thr;
@property (nonatomic , strong) NSMutableArray * fir;
@property (nonatomic , strong) NSMutableArray * sat;
@property (nonatomic , strong) NSMutableArray * sun;
@property (nonatomic , strong) NSMutableArray * weekend;




@end

@implementation THMainViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
//    THLog(@"main%@",_cookie);
    self.view.backgroundColor = [UIColor whiteColor];
    self.bgView = [[UIView alloc] init];
    self.bgView.frame = self.view.frame;
    [self.view addSubview:self.bgView];
   

  
//    self.navigationItem.title = @"第八周";
    self.btnArray = [[NSMutableArray alloc] init];
    NSArray * array = [NSArray arrayWithObjects:@"一",@"二",@"三",@"四",@"五", @"六", @"七", nil];
    for (int i = 0; i<7; i ++) {
        UIButton * button = [[UIButton alloc] initWithFrame:CGRectMake(screenW/7*i,80, screenW/7, 40)];
        [button setTitle:[array objectAtIndex:i] forState:UIControlStateNormal];
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [button setTitleColor:[UIColor redColor] forState:UIControlStateSelected];
         button.titleLabel.font = [UIFont systemFontOfSize:20];
        [button addTarget:self action:@selector(buttonSelected:) forControlEvents:UIControlEventTouchUpInside];
        button.tag = i;

//        UIImageView *btnimage = [[UIImageView alloc] init];
//        btnimage.image = [UIImage imageNamed:@"button"];
//        [button insertSubview:btnimage belowSubview:button.titleLabel];
//        [btnimage mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.center.equalTo(button);
//            make.size.mas_equalTo(CGSizeMake(25, 25));
//        }];
        
        [self.btnArray addObject:button];
        [self.view addSubview:button];
    }
    
    
    
    [self getCurrentDay];
    
    self.currentBtn = [[UIButton alloc] init];
    self.currentBtn = self.btnArray[_week];
    self.currentBtn.selected = YES;
    
    [self scrollView];
    
    [self getClassTable:^(NSMutableDictionary *dictionary) {
        
        _result = dictionary;
        _weekend = [NSMutableArray arrayWithObjects:_mon,_tues,_wed,_thr,_fir,_sat,_sun, nil];
        _resultArray = [NSMutableArray arrayWithObjects:_result[@"0"],_result[@"1"],_result[@"2"], _result[@"3"],_result[@"4"], _result[@"5"],_result[@"6"],nil];
        
        for (int i = 0; i < 7; i++) {
            if (_resultArray[i]) {
                //当天课存在，
                NSMutableArray *model = [NSMutableArray array];
                for (NSDictionary *dic in _resultArray[i]) {
                        THClass *class = [THClass classWithDic:dic];
                        [model addObject:class];
                }
                _weekend[i] = model;
                
            }
        }

        for (int i = 0; i < 7; i++) {
            [_tableArray[i] reloadData];
        }
        UINavigationController *historyNav = [self.tabBarController.viewControllers objectAtIndex:1];
        THHistoryViewController *history = [[THHistoryViewController alloc] init];
        history = [historyNav.viewControllers objectAtIndex:0];
        history.weekModel = _weekend;
        history.cookie = _cookie;
    }];
 
    
}


- (NSInteger)getCurrentDay{
    //获得当前星期几
    NSDate *data = [NSDate date];
    //IOS7
//    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    //ios8
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSTimeZone *timeZone = [[NSTimeZone alloc] initWithName:@"Asia/Shanghai"];
    [calendar setTimeZone:timeZone];
    NSDateComponents *comps = [[NSDateComponents alloc] init];
//    NSInteger unitFlags = NSYearCalendarUnit |
//    NSMonthCalendarUnit |
//    NSDayCalendarUnit |
//    NSWeekdayCalendarUnit |
//    NSHourCalendarUnit |
//    NSMinuteCalendarUnit |
//    NSSecondCalendarUnit;
    NSInteger unitFlags = NSCalendarUnitYear | NSCalendarUnitWeekday;
    comps = [calendar components:unitFlags fromDate:data];
    NSInteger week = [comps weekday];
    _week = week;
    if (_week == 1) {
        _week = 6;
    }else if (_week == 2){
        _week = 0;
    }else{
        _week = _week-2;
    }
    
    return week;
}


- (void)buttonSelected:(UIButton*)sender{
    self.currentBtn.selected = NO;
    self.currentBtn = sender;
    if (_tmpBtn == nil){
        sender.selected = YES;
        _tmpBtn = sender;
//        UIImage *image = [UIImage imageNamed:@"button"];
//        [sender setImage:image forState:UIControlStateNormal];
//        sender.imageView.contentMode = UIViewContentModeCenter;
//        sender.imageView.clipsToBounds = YES;
//        sender.titleLabel.transform = CGAffineTransformMakeTranslation(-10, 0);
    
    }//第一次点击 _tmpbtn记录当前选中的btn
    else if (_tmpBtn !=nil && _tmpBtn == sender){
        sender.selected = YES;
        
    }//第一次与第二次点击相同的
    else if (_tmpBtn!= sender && _tmpBtn!=nil){
        _tmpBtn.selected = NO;
        sender.selected = YES;
        _tmpBtn = sender;
    }//第二次点击与第一次不同，把第一次按钮tmpbtn设置为NO，然后再记入第二次
    
    CGFloat x = sender.tag*screenW;
    [self.scrollbg setContentOffset:CGPointMake(x, 0) animated:NO];
    
    
}

- (UIScrollView *) scrollView{
  
    if (!_scrollbg) {
        NSArray *colors = @[[UIColor blueColor],[UIColor redColor],[UIColor yellowColor],[UIColor greenColor]];
        _scrollbg = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 130, screenW, screenH-48-130)];
        _scrollbg.backgroundColor = [UIColor redColor];
        [self.view addSubview:_scrollbg];
        _scrollbg.pagingEnabled = YES;
        _scrollbg.contentSize = CGSizeMake(7*screenW, 0);
        _scrollbg.delegate = self;
        _scrollbg.bounces = NO;
        _scrollbg.showsHorizontalScrollIndicator = NO;
        self.tableArray = [[NSMutableArray alloc]init];
        for (int i = 0; i < 7; i++) {
            self.tableview = [[UITableView alloc] initWithFrame:CGRectMake(i*screenW, 0, screenW, _scrollbg.frame.size.height)];
            self.tableview.tag = i;
            self.tableview.delegate = self;
            self.tableview.dataSource = self;
            self.tableview.backgroundColor = colors[arc4random()%4];
            self.tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
            self.tableview.bounces = NO;
            self.tableview.rowHeight = 120;
            [self.scrollbg addSubview:self.tableview];
            [self.tableArray addObject:self.tableview];
           
            
        }
        
        CGFloat x = _currentBtn.tag*screenW;
        [_scrollbg setContentOffset:CGPointMake(x, 0) animated:YES];
    }
    
    return _scrollbg;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    for (int i = 0; i < 7; i++) {
        if (tableView == _tableArray[i]) {
            NSArray *array = _weekend[i];
            
            return array.count;
        }
    }
    
    
    return 0;
    
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPat{
    
    for (int i = 0; i < 7; i++) {
        
        if (tableView == _tableArray[i]) {
             THClass *class = _weekend[i][indexPat.row];
            static NSString *ID = @"cell";
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
            if (!cell) {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];
//                cell.backgroundColor = [UIColor grayColor];
                UILabel *location = [[UILabel alloc] initWithFrame:CGRectMake(screenW/2, 40, screenW/2, 40)];
//                THLog(@"%f",cell.frame.size.height);
                location.text = class.venue;
//                location.backgroundColor = [UIColor redColor];
                [cell addSubview:location];
                UILabel *nameOfClass = [[UILabel alloc] initWithFrame:CGRectMake(0, 40, screenW/2, 40)];
                nameOfClass.text = class.courseName;
                nameOfClass.font = [UIFont systemFontOfSize:20];
                location.font = [UIFont systemFontOfSize:20];
//                nameOfClass.backgroundColor = [UIColor blueColor];
                [nameOfClass setTextAlignment:NSTextAlignmentCenter];
                [cell addSubview:nameOfClass];
                UILabel *timeOfClass = [[UILabel alloc] initWithFrame:CGRectMake(0, 80, screenW/2, 40)];
                timeOfClass.text = [NSString stringWithFormat:@"上课时间 %@ 节",class.lessonPeriod];
                [timeOfClass setTextColor:[UIColor grayColor]];
                [timeOfClass setTextAlignment:NSTextAlignmentCenter];
                [cell addSubview:timeOfClass];
                UILabel *courseNo = [[UILabel alloc] initWithFrame:CGRectMake(screenW/2, 80, screenW/2, 40)];
                courseNo.text = [NSString stringWithFormat:@"课程代码:%@",class.courseNo];
                [courseNo setTextColor:[UIColor grayColor]];
                [cell addSubview:courseNo];
                
                timeOfClass.font = [UIFont systemFontOfSize:15];
                courseNo.font = [UIFont systemFontOfSize:15];
                
                UIView *underLine = [[UIView alloc] initWithFrame:CGRectMake(0, 115, screenW, 5)];
                underLine.backgroundColor = [UIColor redColor];
                [cell addSubview:underLine];
            
                
            }
           

            return cell;
        }
    }
    return nil;
    
     }


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    for (int i = 0; i < 7; i++) {
        if (tableView == _tableArray[i]) {
            THClass *class = _weekend[i][indexPath.row];
            THRollcallViewController *rollcall = [[THRollcallViewController alloc] init];
            rollcall.courseId = class.courseId;
            rollcall.weekOrdinal = class.weekOrdinal;
            [self.navigationController pushViewController:rollcall animated:YES];
        }
    }
    

   
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [tableView deselectRowAtIndexPath:[tableView indexPathForSelectedRow] animated:YES];
    });
}


- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    self.currentBtn.selected = NO;
    int numberbtn = scrollView.contentOffset.x / screenW;
    self.currentBtn = self.btnArray[numberbtn];
    self.currentBtn.selected = YES;
    
}


- (void)getClassTable:(void(^)( NSMutableDictionary *dictionary))success{  
    NSURL* URL = [NSURL URLWithString:@"http://120.26.83.51/demo/get_course/"];
    NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:URL cachePolicy:1 timeoutInterval:2.0f];
    request.HTTPMethod = @"GET";
    [request addValue:_cookie forHTTPHeaderField:@"Cookie"];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        id result = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
        NSMutableDictionary *array = result;
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            if (success) {
                success(array);
            }
        }];
    }];
    
}

- (void)rollcall{
 
}


@end
